import React, {useEffect, useState} from 'react';
import {
    Box,
    Button,
    Card,
    CardContent,
    CardHeader,
    Divider,
    FormControl,
    IconButton,
    InputLabel,
    MenuItem,
    Paper,
    Select, Stack,
    styled,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TablePagination,
    TableRow,
    Tooltip, Typography
} from "@mui/material";
import CircularProgress from "@mui/material/CircularProgress";
import {DatePicker} from '@mui/x-date-pickers/DatePicker';

import {list, paid} from "../../api/finance/order";
import {list as listCourse} from "../../api/info/course";
import {list as listStudent} from "../../api/school/student";
import ToggleButton from "@mui/material/ToggleButton";

import PendingIcon from '@mui/icons-material/Pending';
import PaidIcon from '@mui/icons-material/Paid';
import DoneIcon from '@mui/icons-material/Done';
import RefreshIcon from '@mui/icons-material/Refresh';
import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty';
import SearchIcon from '@mui/icons-material/Search';
import AddIcon from '@mui/icons-material/Add';
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import ExpandIcon from '@mui/icons-material/Expand';
import CompressIcon from '@mui/icons-material/Compress';
import PersonIcon from '@mui/icons-material/Person';
import PeopleIcon from '@mui/icons-material/People';

import {RestartAlt} from "@mui/icons-material";

import {formatMoney} from "../../utils/math";
import {YYYYMMDD, formatDate} from "../../utils/time";

import dayjs from "dayjs";
import LoadingButton from "@mui/lab/LoadingButton";

import ToggleButtonGroup, {toggleButtonGroupClasses,} from '@mui/material/ToggleButtonGroup';
import CreateOrder from "./create-order";

import {alert} from "../common/alert";
import {confirm} from "../common/confirm";
import PageNavBar from "../common/page-nav-bar";

const defaultForm = Object.freeze({
    page: 1,
    start: dayjs().startOf('month').startOf('day'),
    end: dayjs().startOf('day'),
    courseId: 0,
    parentId: 0,
    paid: true,
    grouped: null,
    completed: null,
});

const StyledToggleButtonGroup = styled(ToggleButtonGroup)(({theme}) => ({
    [`& .${toggleButtonGroupClasses.grouped}`]: {
        margin: theme.spacing(0.5),
        border: 0,
        borderRadius: theme.shape.borderRadius,
        [`&.${toggleButtonGroupClasses.disabled}`]: {
            border: 0,
        },
    },
    [`& .${toggleButtonGroupClasses.middleButton},& .${toggleButtonGroupClasses.lastButton}`]:
        {
            marginLeft: -1,
            borderLeft: '1px solid transparent',
        },
}));

function Order() {

    const [total, setTotal] = useState(0);
    const [page, setPage] = useState(1);
    const [size, setSize] = useState(10);

    const [form, setForm] = useState({...defaultForm});

    const [loading, setLoading] = useState(false);
    const [orders, setOrders] = useState([]);

    const [courses, setCourses] = useState([]);
    const [parents, setParents] = useState([]);

    const [searching, setSearching] = useState(false);
    const [showForm, setShowForm] = useState(true);
    const [dense, setDense] = useState(true);

    const [create, setCreate] = useState(false);

    function loadOrders(query) {
        setLoading(true);

        list({
            ...query,
            start: formatDate(query.start),
            end: formatDate(query.end),
        }).then(data => {

            setTotal(data.total);
            setPage(data.page);
            setSize(data.size);
            setOrders(data.list);

            setLoading(false);
            setSearching(false);
        });
    }

    function loadCourses() {
        listCourse().then(data => {
            setCourses(data || []);
        });
    }

    function loadStudents() {
        listStudent().then(data => {
            if (data && data.length > 0) {
                const list = data.filter(e => e.role === 'PARENT');
                list.forEach(e => {
                    e.children = data.filter(s => s.parentId === e.id);
                });
                setParents(list);
            } else {
                setParents([]);
            }
        });
    }

    useEffect(() => {
        loadOrders(defaultForm);
        loadCourses();
        loadStudents();
    }, []);

    function handleChange(event) {
        const {name, value} = event.target;
        setForm({...form, [name]: value});
    }

    function handlePaid(order, value) {
        value && confirm(`将为你修改订单【${order.id}】的支付状态为【已支付】，确定吗？`)
            .then(choice => choice && paid(order.id))
            .then(data => {
                if (data) {
                    const newOrders = orders.map(o => {
                        if (o.id === order.id) {
                            o.paid = true;
                        }
                        return o;
                    });
                    setOrders(newOrders);
                    alert(`订单 【${order.id}】 支付状态更新成功`);
                }
            });
    }

    return (
        <Box p={4} display="flex" gap={4} flexDirection="column">
            <Card raised sx={{padding: 2, boxSizing: 'border-box', width: '100%'}}>
                <CardHeader
                    title={
                        <Stack direction="row" alignItems="center" spacing={1}>
                            <Typography variant="h5">订单</Typography>
                            {loading && <CircularProgress color="inherit" size={24}/>}
                        </Stack>
                    }
                    action={
                        <Box mr={1}>
                            <IconButton onClick={() => setShowForm(!showForm)}>
                                {showForm ? <VisibilityOffIcon/> : <VisibilityIcon/>}
                            </IconButton>

                            <IconButton onClick={() => setDense(!dense)}>
                                {dense ? <ExpandIcon/> : <CompressIcon/>}
                            </IconButton>

                            <IconButton onClick={() => loadOrders(form)}><RefreshIcon/></IconButton>

                            <IconButton onClick={() => setCreate(true)}><AddIcon/></IconButton>
                        </Box>
                    }/>

                <CardContent>
                    {showForm && <Box mb={4} display="flex" gap={2} alignItems="center" flexWrap="wrap">
                        <DatePicker format={YYYYMMDD} sx={{width: 160}}
                                    label="开始日期" value={form.start}
                                    onChange={v => setForm({...form, start: v})}/>

                        <DatePicker format={YYYYMMDD} sx={{width: 160}}
                                    label="结束日期" name="end" value={form.end}
                                    onChange={v => setForm({...form, end: v})}/>

                        <FormControl sx={{width: 160}}>
                            <InputLabel>课程</InputLabel>
                            <Select value={form.courseId} label="课程" name="courseId" onChange={handleChange}>
                                <MenuItem value="0">选择课程</MenuItem>
                                <Divider/>
                                {courses.map(e => <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                            </Select>
                        </FormControl>

                        <FormControl sx={{width: 140}}>
                            <InputLabel>付款人</InputLabel>
                            <Select value={form.parentId} label="付款人" name="parentId" onChange={handleChange}>
                                <MenuItem value="0">选择付款人</MenuItem>
                                <Divider/>
                                {parents.map(e => <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                            </Select>
                        </FormControl>

                        <Paper
                            elevation={0}
                            sx={{
                                display: 'flex',
                                border: (theme) => `1px solid ${theme.palette.divider}`,
                                flexWrap: 'wrap',
                            }}
                        >

                            <StyledToggleButtonGroup name="paid" value={form.paid} exclusive
                                                     onChange={(_, newValues) => {
                                                         setForm({...form, paid: newValues});
                                                     }}>
                                <Tooltip title="未支付" placement="top" arrow>
                                    <ToggleButton value={false}><PendingIcon/></ToggleButton>
                                </Tooltip>
                                <Tooltip title="已支付" placement="top" arrow>
                                    <ToggleButton value={true}><PaidIcon/></ToggleButton>
                                </Tooltip>
                            </StyledToggleButtonGroup>

                            <Divider flexItem orientation="vertical" sx={{mx: 0.5, my: 1}}/>

                            <StyledToggleButtonGroup name="grouped" value={form.grouped} exclusive
                                                     onChange={(_, newValues) => {
                                                         setForm({...form, grouped: newValues});
                                                     }}>
                                <Tooltip title="未分班" placement="top" arrow>
                                    <ToggleButton value={false}><PersonIcon/></ToggleButton>
                                </Tooltip>
                                <Tooltip title="已分班" placement="top" arrow>
                                    <ToggleButton value={true}><PeopleIcon/></ToggleButton>
                                </Tooltip>
                            </StyledToggleButtonGroup>

                            <Divider flexItem orientation="vertical" sx={{mx: 0.5, my: 1}}/>

                            <StyledToggleButtonGroup name="completed" value={form.completed} exclusive
                                                     onChange={(_, newValues) => {
                                                         setForm({...form, completed: newValues});
                                                     }}>
                                <Tooltip title="未结课" placement="top" arrow>
                                    <ToggleButton value={false}><HourglassEmptyIcon/></ToggleButton>
                                </Tooltip>
                                <Tooltip title="已结课" placement="top" arrow>
                                    <ToggleButton value={true}><DoneIcon/></ToggleButton>
                                </Tooltip>
                            </StyledToggleButtonGroup>
                        </Paper>

                        <Button startIcon={<RestartAlt/>} variant="contained" color="primary"
                                onClick={() => setForm({...defaultForm})}>
                            重置
                        </Button>
                        <LoadingButton startIcon={<SearchIcon/>} variant="contained" color="primary"
                                       type="submit" loading={searching}
                                       loadingIndicator={<CircularProgress color="inherit" size={24}/>}
                                       onClick={() => {
                                           setSearching(true);

                                           const updatedForm = {...form, page: 1};
                                           setForm(updatedForm);
                                           loadOrders(updatedForm);
                                       }}>
                            查询
                        </LoadingButton>
                    </Box>}

                    <TableContainer component={Paper}>
                        <Table size={dense ? 'small' : 'medium'}>
                            <TableHead>
                                <TableRow>
                                    <TableCell width={'30px'}>ID</TableCell>
                                    <TableCell>课程</TableCell>
                                    <TableCell width={'160px'}>学员</TableCell>
                                    <TableCell width={'120px'}>金额（元）</TableCell>
                                    <TableCell width={'60px'} align={"center"}>支付状态</TableCell>
                                    <TableCell width={'60px'} align={"center"}>学习状态</TableCell>
                                    <TableCell width={'160px'} align={"center"}>时间</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {orders.map(e => (
                                    <TableRow key={e.id}>
                                        <TableCell component="th" scope="row">{e.id}</TableCell>
                                        <TableCell>{e.course}</TableCell>
                                        <TableCell>{e.parent} {e.student ? `(${e.student})` : ''}</TableCell>
                                        <TableCell>{formatMoney(e.amount)}</TableCell>
                                        <TableCell>
                                            <ToggleButtonGroup
                                                disabled={e.paid} value={e.paid} exclusive size="small"
                                                onChange={(_, v) => handlePaid(e, v)}>
                                                <ToggleButton value={false}><PendingIcon/></ToggleButton>
                                                <ToggleButton value={true}><PaidIcon/></ToggleButton>
                                            </ToggleButtonGroup>
                                        </TableCell>

                                        <TableCell>
                                            <ToggleButtonGroup disabled exclusive size="small">
                                                {!e.grouped && <ToggleButton value={0}><PersonIcon/></ToggleButton>}
                                                {e.grouped && <ToggleButton value={0}><PeopleIcon/></ToggleButton>}
                                                {!e.completed &&
                                                    <ToggleButton value={2}><HourglassEmptyIcon/></ToggleButton>}
                                                {e.completed && <ToggleButton value={3}><DoneIcon/></ToggleButton>}
                                            </ToggleButtonGroup>
                                        </TableCell>

                                        <TableCell>{e.ct}</TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </TableContainer>
                    {total > size && <TablePagination
                        ActionsComponent={PageNavBar}
                        rowsPerPageOptions={[10]}
                        component="div"
                        count={total}
                        rowsPerPage={size}
                        page={page - 1}
                        labelDisplayedRows={({count, page}) =>
                            `第 ${page + 1} 页，共 ${Math.ceil(total / size)} 页，共 ${count} 条数据`}
                        onPageChange={(event, newPage) => {
                            window.scrollTo(0, 0);
                            const updatedForm = {...form, page: newPage + 1};
                            setForm(updatedForm);
                            loadOrders(updatedForm);
                        }}
                    />}
                </CardContent>
            </Card>

            <CreateOrder
                open={create}
                onClose={() => setCreate(false)}
                courses={courses} parents={parents}/>

        </Box>
    );
}

export default Order;
